<template>
  <div ref="el" :style="style" style="position: fixed">
    <div v-if="isShiow">123</div>
    <div class="anniu-box" @click="addAnniu">按钮</div>
    <div v-if="isShiow">456</div>
  </div>
</template>

<script setup>
import { ref } from "vue"
import { useDraggable, useWindowSize, onClickOutside } from "@vueuse/core"

const el = ref(null)
// const x1 = ref(1410)
// const y1 = ref(830)
const isShiow = ref(false)
// 获取浏览器窗口的大小
const { width, height } = useWindowSize()
// 点击事件的执行时间小于200由此可以区分点击事件和拖拽事件
let firstTime = ref(0)
let lastTime = ref(0)

const { x, y, style } = useDraggable(el, {
  initialValue: { x: 0, y: 0 },
  preventDefault: true,
  onStart: () => {
    firstTime.value = new Date().getTime()
  },
  onMove: (position) => {
    if (position.x > width.value - 100) {
      position.x = width.value - 100
    }
    if (position.x < 0) {
      position.x = 0
    }
    if (position.y > height.value - 100) {
      position.y = height.value - 100
    }
    if (position.y < 0) {
      position.y = 0
    }
  },
  onEnd: () => {
    lastTime.value = new Date().getTime()
  }
})
// 控制展开悬浮框的函数
const addAnniu = () => {
  if (lastTime.value - firstTime.value <= 200) {
    // 是否展开
    isShiow.value = !isShiow.value
  }
}
// 点击外部区域可以关闭
onClickOutside(el, () => {
  console.log(el)
  isShiow.value = false
})
</script>

<style lang="less">
.anniu-box {
  width: 100px;
  height: 100px;
  background-color: red;
}
</style>
